
<template>
    <div class="pres-comp-target-comp" ref="compTarget">
         <TitleBox type=2>
            <template #titlecont>
                <span v-lang="{lang: controlSto.language, lgid: -22}">Target</span>
            </template>
        </TitleBox>
        <!-- TODO 1个echart -->
        <div class="chart-box">
            <div class="chart-img-wrap">
                <uiEchart :config="optionType" :vt="dataObj.echartoptVt1" ref="chartType"/>
            </div>
        </div>

        <div class="condition-box">
            <div class="condition-left">
                <SearchDrop class="cond-item">
                    <template #title>
                        <span v-lang="{lang: controlSto.language, lgid: -44}">List sort</span>
                    </template>
                    <template #dropcont>
                        <div class="cond-drop-cont-wrap">
                            <el-radio-group v-model="condObj.sort" @change="toSearch">
                                <div class="cond-radio-wrap">
                                    <el-radio class="cond-radio-item" value="Asc"><span v-lang="{lang: controlSto.language, lgid: -49}"></span></el-radio>
                                    <el-radio class="cond-radio-item" value="Desc"><span v-lang="{lang: controlSto.language, lgid: -50}"></span></el-radio>
                                </div>
                            </el-radio-group>
                        </div>
                    </template>
                </SearchDrop>
                <SearchDrop class="cond-item">
                    <template #title>
                        <!-- <el-popover placement="top-start">
                            <el-checkbox class="all-choose-cls"
                                v-model="condObj.TypeAll"
                                @change="allChooseType"
                            >
                            <span @click.stop="condObj.TypeAll = !condObj.TypeAll" v-lang="{lang: controlSto.language, lgid: -130}">select all</span>
                        </el-checkbox>
                            <template #reference>
                                <span v-lang="{lang: controlSto.language, lgid: -45}">Type</span>
                            </template>
                        </el-popover> -->
                        <span v-lang="{lang: controlSto.language, lgid: -45}">Type</span>
                    </template>
                    <template #dropcont>
                        <div class="cond-drop-cont-wrap">
                            <el-checkbox class="all-choose-cls"
                                v-model="condObj.TypeAll"
                                @change="allChooseType"
                            >
                                <span @click.stop="condObj.TypeAll = !condObj.TypeAll" v-lang="{lang: controlSto.language, lgid: -130}">select all</span>
                            </el-checkbox>
                            <el-checkbox-group v-model="condObj.type" @change="toSearch">
                                <div class="cond-chbox-wrap">
                                    <el-checkbox class="cond-chbox-item" v-for="item in dataObj.typeList" :key="'type_' + item.id" :value="item.typeCode" :label="item.typeName"  />
                                </div>
                            </el-checkbox-group>
                        </div>
                    </template>
                </SearchDrop>
            </div>
            <div class="condition-right">
                <div class="ipt-cont">
                    <el-input class="ipt-search" clearable="true" v-model="condObj.searchword" autofocus :placeholder="searchPlace" />
                </div>
                <SearchBtn class="search-item" @click.stop="toSearch"/>

                <TableFilter class="search-item" :column="dataObj.columnList" :filterKey="condObj.filterKey" @onChg="chgTableCol"/>

                <SearchLoad  type="prescrTarget" :uiCode="condObj.uiCode" :para="{
                    'content': condObj.searchword,
                    'langCode': controlSto.language == 1 ? 'ENG' : 'CHN',
                    'prescriptionId': detailId,
                    'sortType': condObj.sort,
                    'type': condObj.type.join(','),
                    'uiTypeCode': condObj.uiCode
                }"/>
            </div>
        </div>


        <div class="cont-box">
            <uiTable
                :config="dataObj.tableConfig"
                :columnConfig="dataObj.columnConfig"
                :loading="isLoading" 
                :data="dataObj.dataList"
                :key="dataObj.searchTablevt">
                <template #[condObj.ingredientField]="{ row }">
                    <div class="jump-box" @click.stop="toClkItem(row, 1)"><span>{{row[condObj.ingredientField]}}</span></div>
                </template>
                <template #[condObj.herbField]="{ row }">
                    <el-tooltip placement="top" :content="row[condObj.herbField]" v-if="row[condObj.herbField] && row[condObj.herbField].length > 20">
                        <div class="jump-box table-jump-name" @click.stop="toClkItem(row, 2)"><span>{{row[condObj.herbField]}}</span></div>
                    </el-tooltip>
                    <div v-else>
                        <div class="jump-box" @click.stop="toClkItem(row, 2)"><span>{{row[condObj.herbField]}}</span></div>
                    </div>
                </template>
            </uiTable>
            <div class="page-box" v-if="condObj.total > 10">
                <uiPagination
                    :total="condObj.total" :pageSize="condObj.pageSize" :pageIndex="condObj.pageIndex"
                    @onSizeChange="chgSize" @onCurrentChange="chgCurrnt"/>
            </div>
        </div>
    </div>
</template>

<script setup>
    import { ref, reactive, toRefs, computed, onBeforeMount, watch, onMounted } from 'vue'
    import { useIntersectionObserver } from '@vueuse/core';
    import TitleBox from '@/components/TitleBox.vue'
    import SearchBtn from '@/components/SearchBtn.vue'
    import uiEchart from '@/components/ui-echart.vue'
    import TableFilter from '@/components/TableFilter.vue'
    import SearchLoad from '@/components/SearchLoad.vue'
    import uiTable from '@/components/ui-table.vue'
    import uiPagination from '@/components/ui-pagination.vue'
    import SearchDrop from '@/components/SearchDrop.vue'
    import { useRouter } from 'vue-router'

    import { langTxt, getFilterThArr, getFilterLangArr,computedgraphOptions } from '@/utils/util'
    import { getTableThList, getPrescriptionCompTarget, getPrescriptopnTargetStatistic, getTargetType } from '@/service/tcm'
    // import { typeList } from '@/utils/database'
    import { controlStore } from '@/stores/control'
    import { debounce } from 'lodash'
    
    const emitter = defineEmits(['toCalc']);
    const router = useRouter();
    const props = defineProps({
        detailId: {
            type: [Number, String],
            default: ''
        }
    });
    const { detailId } = toRefs(props);
    
    let searchDebounce = null;
    const compTarget = ref(null);

    const controlSto = controlStore();
    const isLoading = ref(true);

    const condObj = reactive({
        ingredientField: '100716826576556898',
        idField: '100716826576556896',
        herbField: '100716826576556899',
		searchword: '',
		filterKey: 'pres4',
        uiCode: 'prescription_composition_target',
        type: [],
        word: '',
        total: 0,
        pageSize: 10,
        pageIndex: 1,
        sort: 'Asc',
        TypeAll: true
	});

	const dataObj = reactive({
        typeList: [],
		searchTablevt: 1,
		echartoptVt1: 1,
		columnList: [],
		tableConfig: {
			// size: 'small',
			'tooltip-effect': 'dark',
			'highlight-current-row': true,
			stripe: true,
			'header-cell-style': { background: '#BC9F77', color: '#FFF' },
		},
		columnConfig: [],
		dataList: []
	});

    const searchPlace = computed(() => {
		return langTxt(controlSto.language, '-15');
	});
    const optionType = computedgraphOptions(langTxt(controlSto.language, '-107'), '', [], true, 'center', '50%', ['30%', '50%'],'', 1)
    const chartType = ref(null);

    onBeforeMount(()=> {
        // initDebounce();
		
        toGetTargetType();
        const {stop} = useIntersectionObserver(
            compTarget,
            ([{ isIntersecting }], observerElement) => {
                if (isIntersecting) {
                    // 停止监听，如果你只想知道一次可视性变化
                    getTableTh();
                    initDebounce();
                    getDataList();
                    //阻止再次请求
                    stop()
                }
            },
            {
                threshold: 0, // 当交叉框达到视窗的这部分时触发
            }
        );
    });

    const initDebounce = () => {
        searchDebounce = debounce((e) => {
           getDataList();
        }, 1000);
    };

    const toClkItem = (row, type) => {
        if(type == 1) {
            router.push({ name: 'ingrdetail' , query: {id: row.ingrId} });
        } else {
            router.push({ name: 'herbdetail' , query: {id: row.herbId} });
        }
    }

    const getTableTh = () => {
        let params = {
            uiCode: condObj.uiCode,
            langCode: 'ENG,CHN'
        };

        getTableThList(params).then((res) => {
            if (res.success) {
                let arr = res.data || [];
                let thArr = getFilterThArr(arr, dataObj.filterKey);
        		let langArr = getFilterLangArr(thArr);
        		controlSto.setLangList(langArr);
        		dataObj.columnList = thArr;
            }
        }).catch(() => {});

        // let thArr = getFilterThArr(arr, condObj.filterKey);
        // let langArr = getFilterLangArr(thArr);
        // controlSto.setLangList(langArr);
        // dataObj.columnList = thArr;
    };
    const toGetTargetType = () => {
        getTargetType({langCode: controlSto.language == 1 ? 'ENG' : 'CHN'}).then(res => {
            if (res.success && res.data) {
                dataObj.typeList = res.data;
                res.data.forEach(e => {
                    condObj.type.push(e.typeCode)
                })
                toGetPrescriptopnTargetStatistic()
            }
        })
    }
    const toGetPrescriptopnTargetStatistic = () => {
        getPrescriptopnTargetStatistic({prescriptionId:detailId.value,content: condObj.searchword}).then(res => {
            if(res.success && res.data) {
                let typeStatistic = [];
                for(let key in res.data) {
                    dataObj.typeList.forEach(element => {
                        if(element.typeCode == key) {
                            typeStatistic.push({name: element.typeName, value: res.data[key], typeCode: element.typeCode})
                        }
                    });
                }
                optionType.series[0].data = typeStatistic;
                optionType.title.text = langTxt(controlSto.language, '-107');
                optionType.toolbox.feature.saveAsImage.title = controlSto.language == 1 ? 'Download' : '下载';
                typeStatistic.length < 5 ? optionType.legend.top = 'center' : ''
                chartType.value.initEchart();
            }
        })
    }
    const chgTableCol = (e) => {
		dataObj.columnConfig = e || [];
		dataObj.searchTablevt = new Date().valueOf();
        emitter('toCalc');
    };

    
    const toGetData = () => {
        searchDebounce && searchDebounce();
    };

    const getDataList = () => { // getPrescriptionCompTarget
      let params = {
            langCode: controlSto.language == 1 ? 'ENG' : 'CHN',
            prescriptionId: detailId.value,
            content: condObj.word,
            uiTypeCode: condObj.uiCode,
			pageNo: condObj.pageIndex || 10,
			pageSize: condObj.pageSize || 1,
            sortType: condObj.searchword,
            targetType: condObj.type.join(',')
        };
        isLoading.value = true;
        getPrescriptionCompTarget(params).then((res) => {
            isLoading.value = false;
            if (res.success && res.data && res.data.records) {
                res.data.records.forEach(e => {
                    if (e[condObj.ingredientField]) {
                        const _indexIngr = e[condObj.ingredientField].indexOf('||');
                        const ingrId = e[condObj.ingredientField].slice(_indexIngr + 2);
                        e.ingrId = ingrId;
                        e[condObj.ingredientField] = e[condObj.ingredientField].slice(0, _indexIngr);
                    }
                    if(e[condObj.herbField]) {
                        const _indexHerb = e[condObj.herbField].indexOf('||');
                        const herbId = e[condObj.herbField].slice(_indexHerb + 2);
                        e.herbId = herbId;
                        e[condObj.herbField] = e[condObj.herbField].slice(0, _indexHerb);
                    }
                })
                dataObj.dataList = res.data.records || [];
                condObj.total = res.data.totalCount || 0;
            }
        }).catch(() => {
            isLoading.value = false;
        });

        emitter('toCalc');
    };


        
    const chgSize = (e) => {
        condObj.pageSize = e || 10;
        toGetData();
    };
    const chgCurrnt = (e) => {
        condObj.pageIndex = e || 1;
        toGetData();
    };
    const toSearch = () => {
        condObj.word = condObj.searchword;
        condObj.pageIndex = 1;
        toGetData();
    };
    const allChooseType = () => {
		if(condObj.type.length == dataObj.typeList.length) {
			condObj.type = [];
		} else {
			condObj.type = [];
			dataObj.typeList.forEach(e => {
				condObj.type.push(e.typeCode)
			})
		}
	}
    watch(() => controlSto.language, (nv, ov) => {
		if(nv != ov && ov) {
			dataObj.echartoptVt1 = new Date().valueOf();
            toGetData();
		}
	}, { immediate: true });
    watch(() => condObj.type, (n, v) => {
		if(n != v) {
			toSearch();
			if(n.length == dataObj.typeList.length) condObj.TypeAll = true;
			else condObj.TypeAll = false;
		}
	})

</script>


<style lang="scss" scoped>
    .pres-comp-target-comp {
        margin-bottom: 8px;
        .chart-box {
            margin: 24px 0 0;
            display: flex;
            justify-content: center;
            .chart-img-wrap {
                height: 240px;
                width: 50%;
                max-width: 500px;
                padding: 8px 12px 0;
            }
        }
        .condition-box {
            display: flex;
            padding: 30px 0;
            justify-content: space-between;
            // border: 1px solid red;
            .condition-left {
                .cond-item {
                    margin-right: 16px;
                }
            }
            .condition-right {
                .ipt-cont {
                    display: inline-block;
                    padding-right: 16px;
                    .ipt-search {
                        // width: 300px;
                    }
                }
                .search-item {
                    margin-right: 16px;
                }
            }
        }
        .cont-box {
        }
    }
</style>
